package com.tx.core.mybatis.handler;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.*;

/**
 * <pre>
 * 功能简述: JSONTypeHandler
 * </pre>
 *
 * @author PengQingyang
 * 创建时间 [2024/4/10]
 */
@Slf4j
@MappedJdbcTypes({JdbcType.VARCHAR})
@MappedTypes({JSONObject.class})
public class JSONTypeHandler extends BaseTypeHandler<JSONObject> {

    private ObjectMapper mapper = new ObjectMapper();

    @Override
    public JSONObject getNullableResult(ResultSet rs, String columnName) {
        try {
            String value = rs.getString(columnName);
            return mapper.readValue(value, JSONObject.class);
        } catch (Exception e) {
            log.warn("JSONTypeHandler getNullableResult error.",e);
        }
        return null;
    }

    @Override
    public JSONObject getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        try {
            String value = rs.getString(columnIndex);
            return mapper.readValue(value, JSONObject.class);
        } catch (Exception e) {
            log.warn("JSONTypeHandler getNullableResult error.",e);
        }
        return null;
    }

    @Override
    public JSONObject getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        try {
            String value = cs.getString(columnIndex);
            return mapper.readValue(value, JSONObject.class);
        } catch (Exception e) {
            log.warn("JSONTypeHandler getNullableResult error.",e);
        }
        return null;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, JSONObject parameter, JdbcType jdbcType)
            throws SQLException{
        if (parameter == null) {
            ps.setNull(i, Types.VARCHAR);
        } else {
            ps.setString(i, JSON.toJSONString(parameter));
        }
    }
}
